package controllers

import (
	"net/http"
	"html/template"
	"strings"
	"log"
)


// -------------------------
// Data Struct.
type Pager struct {
	Current int
	Total int
	Size int
	Next int
	Prev int
	NextPageUrl string
	PrevPageUrl string
}


// 资源信息的属性
type Item struct {
	Id string
	Title string
	Path string
	Url string
	IsRoot bool
	IsDir bool
	Size int64
	Pid string
  MimeType string
	ModAt string
	ApprovedAt string
	Status int // 0: normal, -1: todo, -2: remove, 1: star
	Views int
	Stars int
	Recommend bool // false: no, true: yes
	IsPreview bool
}

type ItemArray []Item

//Len()
func (array ItemArray) Len() int {
	return len(array)
}

//Less(): ModAt
func (array ItemArray) Less(i, j int) bool {
	return array[i].ModAt > array[j].ModAt
}

//Swap()
func (array ItemArray) Swap(i, j int) {
	array[i], array[j] = array[j], array[i]
}


var (
	t = template.Must(template.ParseGlob("templates/*"))
)
// ---------------------------------
// The template render method.
func RenderTemplate(w http.ResponseWriter, tmpl string, data interface{}) {
	err := t.ExecuteTemplate(w, tmpl, data)
	if err != nil {
		log.Fatal(err)
		http.Error(w, "error 500:" + " " + err.Error(), http.StatusInternalServerError)
	}
}

func _ParseUrlParams(r *http.Request)( map[string]string ) {
	params := make(map[string]string)
	r.ParseForm()
	for k, v := range r.Form {
		if len(v) == 1 {
			params[k] = v[0]
		}else if len(v) == 0 {
			// no data, no need to set data
		}else if len(v) > 1 {
			params[k] = strings.Join(v, ",")
		}
	}

	return params
}

//---------------------------------------
// Util Functions.

func checkErr(err error) {
	if err != nil {
		log.Fatal(err)
		panic(err)
	}
}
func IsEmpty(str string)(bool){

	return str == ""
}

func Max(a, b int) int {
	if a < b {
		return b
	}
	return a
}
func Min(a, b int) int {
	if a > b {
		return b
	}
	return a
}

///*
// 分页
func _MakePager(array ItemArray, current int) ([]Item, bool, bool){
	total := len(array)
	start := (current - 1) * Limit
	end := current * Limit
	hasPre := current > 1
	hasNext := total > (current * Limit)

	if current < 1 {
		start = 0
	}
	if start > total {
		// overflow
		return []Item{}, hasPre, hasNext
	}

	if end > total {
		end = total 
	}
	return array[start: end], hasPre, hasNext
}//*/